import {Table,Icon,Row,Col,Button,Spin} from 'antd'
import {WeaTools,WeaInput,WeaSelect,WeaBrowser} from 'ecCom'
import './style/index.css'
import equal from 'deep-equal'

class WeaTableEdit extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
			columns: [],
			datas: [],
			current: 1,
			showGroup: props.showGroup ? props.showGroup : false,
		}
		this.onEdit = this.onEdit.bind(this);
		this.doAdd = this.doAdd.bind(this);
	}
	componentDidMount() {
		const { datas = [], columns = [] } = this.props;
		columns.length > 0 && this.setState(datas.length > 0 ? {datas: this.addKeytoDatas(datas),columns} : {columns})
	}
	componentWillReceiveProps(nextProps,nextState) {
		const { columns = [], datas = [] } = this.props;
		const _columns = nextProps.columns || [];
		const _datas = nextProps.datas || [];
		!equal(columns,_columns) && this.setState({columns});
		!equal(datas,_datas) && this.setState({datas: this.addKeytoDatas(_datas)});
	}
	shouldComponentUpdate(nextProps,nextState) {
		return !equal(this.props.datas,nextProps.datas)||
		!equal(this.state,nextState)
	}
	addKeytoDatas(datas){
		let _datas = datas.map((data, i) => {
			let _data = {...data};
			_data.key = i
			return _data
		})
		return _datas
	}
	render() {
		const { datas,showGroup,columns } = this.state;
		const {title,needAdd,needCopy} = this.props;
		return(
			<div className="wea-crm-table-edit" >
				<Row className="wea-title">
                    <Col span="20">
                        <div>{title}</div>
                    </Col>
                    
					<Col span="4" style={{textAlign:"right",paddingRight:10,fontSize:12}}>
						{needAdd &&	<Button type="primary" title='新增' size="small" onClick={this.doAdd}><Icon type="plus" /></Button>}
						<Icon type={showGroup ? 'up' : 'down'} onClick={()=>this.setState({showGroup:!showGroup})}/>
					</Col>
                </Row>
				<Row className="wea-content" style={{display:showGroup ? "block":"none"} }>
					<Col className="wea-form-cell" span={24}>
						<Table 
							columns={this.getColumns()}
							dataSource={datas}
							pagination={false}
							//rowSelection={this.getRowSelection()}
							className="contracter-edit-table"
						/>
					 </Col>
                </Row>
               
            </div>
		)
	}
	getColumns(){
		const { columns } = this.state;
		let _columns = [].concat(columns);
		_columns = _columns.map(col => {
			let _col = { ...col };
			_col.render = ( text, record, index ) => {
				return this.getColRender( _col, text, record, index );
			}
			return _col
		});
		return _columns
	}
	getColRender( _col, text, record, index ){
		const { com ,hasIcon=false,hasadd=false} = _col;
		let _com = [];
		com.map(c => {
			if(typeof c.props === 'object'){
				if(record["notNew"]=="true" && _com.length==0){
					_com.push(<Button type="primary" title='明细' size="small" onClick={()=>crmOpenSPA4Single('/main/crm/contacterView?contacterId='+record.contacterid)}><Icon type="file-text" /></Button>);
				}else if(!record["notNew"]){
					_com.push(c);
				}
			}else{
				const { domkey,viewAttr =2,  formItemType = 'INPUT', options = [], browserConditionParam = {}, width  } = c;
				const _type = formItemType.toUpperCase();
				_com.push(
					<span>
						{ _type === 'INPUT' && !hasIcon && !hasadd &&
							<WeaInput 
								 defaultValue={record[domkey[0]]} 
								value={record[domkey[0]]} 
								style={{width, display: 'inline-block'}}
								onBlur={value => this.onEdit(record, index, domkey[0], value)}
								viewAttr={viewAttr} /> 
						}
						{ _type === 'INPUT' && hasIcon &&
							<div>
								<WeaInput 
									defaultValue={record[domkey[0]]} 
									value={record[domkey[0]]} 
									style={{width:"75%", display: 'inline-block'}}
									onBlur={value => this.onEdit(record, index, domkey[0], value)}
									viewAttr={viewAttr} />
									<a href={`${"tencent://message/?uin="+record[domkey[0]]+"&Site=&Menu=yes"}`} title="点击发起QQ会话"><i className='icon-crm-qq' /></a>
							</div>
						}
						{ _type === 'INPUT' && hasadd &&
							<div>
								<WeaInput 
									defaultValue={record[domkey[0]]} 
									value={record[domkey[0]]} 
									style={{width:"75%", display: 'inline-block'}}
									onBlur={value => this.onEdit(record, index, domkey[0], value)}
									viewAttr={viewAttr} />
									<a onClick={()=>this.props.showRightContactlog(false,record)} title="添加联系记录" style={{marginLeft:"5px"}}><i className="icon-crm-wenjiantianjia"  /></a>
							</div>
						}
						{ _type === 'BROWSER' && 
							<WeaBrowser 
								replaceDatas={this.getBrowerDatas(record, domkey[0])}
								{...browserConditionParam}
								style={{width, display: 'inline-block'}}
								onChange={(ids, names, bDatas) => this.onEdit(record, index, domkey[0], ids, names, bDatas)}
								 /> 
						}
						{ _type === 'SELECT' && 
							<WeaSelect 
								// defaultValue={record[domkey[0]]}
								value={record[domkey[0]]}
								options={options}
								style={{width, display: 'inline-block'}}
								onChange={value => this.onEdit(record, index, domkey[0], value)} /> 
					}
					</span>
				)
			}
		});
		return (
			<div>
				{_com}
			</div>
		)
	}
	getBrowerDatas(record, key){
		let replaceDatas = [];
		if(record[key + 'Name'] !== undefined) {
			let keys = record[key].split(',');
			let values = record[key + 'Name'].split(',');
			if(keys.length === values.length){
				keys.map((k, i) => {
					replaceDatas.push({id: k, name: values[i]});
				});
			}else{
				console.log('浏览按钮数据有误！！，显示名中不能包含有英文逗号" , "');
			}
		}
		return replaceDatas
	}
	onEdit(record, index, key, value, names, bDatas){
		const oldvalue = record[key];
		const { pageSize = 0 } = this.props;
		const { datas, current } = this.state;
		let _datas = [].concat(datas);
		_datas[pageSize * (current - 1) + index][key] = value;
		if(names) _datas[pageSize * (current - 1) + index][key + 'Name'] = names;
		this.setState({datas: _datas});
		this.onChange(_datas);
		if(record.contacterid){
			typeof this.props.onEditChange === 'function' && this.props.onEditChange(record,oldvalue,key,value,index);
		}
		
	}
	doAdd(){
		const { datas } = this.state;
		const {canAdd} =this.props;
		if(canAdd){
			let _datas = [].concat(datas);
			let _data = {...datas[0]};
			for(let k in _data){
				_data[k] = ''
			}
			_data.key = _datas.length;
			_datas.push(_data);
			this.setState({datas: _datas});
			this.onChange(_datas);
		}
		typeof this.props.onAddChange === 'function' && this.props.onAddChange();
	}
	onChange(datas){
		const { columns } = this.state;
		//console.log('onChange datas: ', datas);
		let _datas = datas.map((data, i) => {
			let _data = {...data}
			delete _data.key
			return _data
		})
		//console.log('onChange _datas: ', _datas);
		typeof this.props.onChange === 'function' && this.props.onChange(_datas, columns);
	}
}

export default WeaTableEdit;
